package com.tianji.promotion.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tianji.api.cache.CategoryCache;
import com.tianji.common.utils.CollUtils;
import com.tianji.promotion.controller.CouponScopeController;
import com.tianji.promotion.domain.po.CouponScope;
import com.tianji.promotion.domain.vo.CouponScopeVO;
import com.tianji.promotion.mapper.CouponScopeMapper;
import com.tianji.promotion.service.ICouponScopeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 优惠券作用范围信息 服务实现类
 * </p>
 *
 * @author wjq
 * @since 2023-06-04
 */
@Service
public class CouponScopeServiceImpl extends ServiceImpl<CouponScopeMapper, CouponScope> implements ICouponScopeService {

    @Override
    public void removeByCouponId(Long couponId) {
        remove(new LambdaQueryWrapper<CouponScope>().eq(CouponScope::getCouponId, couponId));
    }

    @Autowired
    private CouponScopeMapper couponScopeMapper;
    @Autowired
    private CategoryCache categoryCache;

    public List<Long> getBizIdsByCouponId(Long couponId) {
        return couponScopeMapper.selectBizIdsByCouponId(couponId);
    }

    @Override
    public List<CouponScopeVO> queryScopeByCouponId(Long couponId) {
        // 1.查询范围
        List<Long> bizIds = getBizIdsByCouponId(couponId);
        // 2.非空处理
        if (CollUtils.isEmpty(bizIds)) {
            return CollUtils.emptyList();
        }

        //categoryCache的getNameByLv3Ids方法获得拼接好的三级分类名称
        List<String> nameByLv3Ids = categoryCache.getNameByLv3Ids(bizIds);

        Map<Long, String> bizIdNameMap = bizIds.stream()
                .filter(Objects::nonNull) // 过滤掉null元素
                .collect(Collectors.toMap(
                        // keyMapper：将每个元素映射为Map的key，即bizId
                        Function.identity(),
                        // valueMapper：将每个元素映射为Map的value，即nameByLv3Ids中元素拼接后的字符串
                        bizId -> {
                            List<String> names = categoryCache.getNameByLv3Ids(Collections.singletonList(bizId));
                            return CollUtils.isEmpty(names) ? null : names.get(0);
                        },
                        // 如果存在重复的key，使用第二个参数的函数来合并value
                        (oldValue, newValue) -> oldValue
                ));

        List<CouponScopeVO> list = new ArrayList<>(bizIdNameMap.size());

        for (Map.Entry<Long, String> entry : bizIdNameMap.entrySet()) {
            CouponScopeVO vo = new CouponScopeVO();
            vo.setId(entry.getKey());
            vo.setName(entry.getValue());
            list.add(vo);
        }
        return list;
    }
}
